package util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.io.IOUtils;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;

import bean.Repertoires;


public class FTPUtil {
	private static final String HOSTNAME_PUBLIC = "5.10.134.204";
	private static final String HOSTNAME_PRIVATE = "172.16.124.55";
	private static final String LOGIN = "ftp_livret";
	private static final String PASSWORD = "acpv";
	private static final String DIRECTORY = "livret-de-suivi";
	private static FTPClient ftpClient = new FTPClient();
	private static InputStream file = null;
	
	public static InputStream getFile(String path){
		try {
			if(file != null){
				ftpClient.completePendingCommand();
			}
			ftpClient.enterLocalPassiveMode();
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
			file = ftpClient.retrieveFileStream("/" + DIRECTORY + "/" + path);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return file;
	}
	
	public static Boolean saveFile(InputStream input, String path, String fileName){
		Boolean result = null;
		try {
			ftpClient.enterLocalPassiveMode();
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            ftpClient.changeWorkingDirectory(DIRECTORY);
            ftpClient.changeWorkingDirectory(path);
			result = ftpClient.storeFile(fileName, input);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}
	
	public static void deleteFile(String path){
		try {
			ftpClient.enterLocalPassiveMode();
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
			ftpClient.deleteFile("/" + DIRECTORY + "/" + path);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void connect(){
		Boolean isPrivate = false;
		try {
			ftpClient.connect(HOSTNAME_PUBLIC);
			ftpClient.login(LOGIN, PASSWORD);
		} catch (IOException e) {
			isPrivate = true;
		}
		if(isPrivate){
			try {
				ftpClient.connect(HOSTNAME_PRIVATE);
				ftpClient.login(LOGIN, PASSWORD);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void disconnect(){
		try {
			ftpClient.logout();
			ftpClient.disconnect();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static File InputStreamToFile(InputStream input, String fileName){
		File tempFile = new File(fileName);
		try {
			FileOutputStream fos = new FileOutputStream(tempFile);
			while (input.available() > 0) {
				fos.write(input.read());
			}
			fos.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return tempFile;
	}
	
	public static void setFile(InputStream files){
		file = files;
	}
}
